package com.guojing.jl.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.nio.ByteBuffer;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

public class TestWriteByteBuf {
    public static void main(String[] args) {

        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(10);
        buffer.writeBytes(new byte[]{1, 2, 3, 4});
        log(buffer);

        // write 一个整数，占4个字节
        buffer.writeInt(5);
        log(buffer);

        // write 一个整数，占4个字节，触发扩容
        buffer.writeInt(6);
        log(buffer);

        /** 输出结果如下**********输出结果*************/
        // read index:0 write index:4 capacity:10
        byte b1 = buffer.readByte();
        System.out.println("read byte1: " + b1);
        log(buffer);

        byte b2 = buffer.readByte();
        System.out.println("read byte2: " + b2);
        byte b3 = buffer.readByte();
        System.out.println("read byte3: " + b3);
        byte b4 = buffer.readByte();
        System.out.println("read byte4: " + b4);
        log(buffer);

        //做个标记
        buffer.markReaderIndex();
//        byte b5 = buffer.readByte();
//        System.out.println("read b5: " + b5);

        int i = buffer.readInt();
        System.out.println("read i1做了标记: " + i);

        int i2= buffer.readInt();
        System.out.println("read i2: " + i2);

        //恢复标记
         buffer.resetReaderIndex();
        System.out.println("read byte恢复之前的标记: " + buffer.readInt());

        log(buffer);




    }

    public static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf.toString());
        System.out.println();
    }
}
